from django.shortcuts import render
from .models import Logger
import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from rest_framework.decorators import api_view
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
from django.http import HttpResponse
from django.template import loader
from device.models import Device
from common.response import JsonResponse
from rest_framework.response import Response
from .serializers import LoggerSerializer
from rest_framework import mixins
import json
from common.constant import CODE_PARAMETER_ERROR, MSG_PARAMETER_ERROR
from user.authentication_module import TokenAuth


def test(request):
    device_list = Device.objects.all().order_by('state')
    template = loader.get_template('websocket_test.html')
    context = {
        'device_list': device_list,
    }
    return HttpResponse(template.render(context, request))


@api_view(['GET'])
def getLogger(request):
    authentication_classes = [TokenAuth]
    try:
        queryParams = request.query_params.dict()
        deviceId = queryParams['deviceId']
        startTime = int(queryParams['startTime'])
        endTime = int(queryParams['endTime'])
    except Exception:
        return JsonResponse(data=None, code=CODE_PARAMETER_ERROR, message=MSG_PARAMETER_ERROR)

    try:
        startTime = datetime.datetime.fromtimestamp(startTime)
        endTime = datetime.datetime.fromtimestamp(endTime)
    except Exception:
        startTime = datetime.datetime.fromtimestamp(startTime/1000)
        endTime = datetime.datetime.fromtimestamp(endTime/1000)

    if(startTime < endTime):
        result = Logger.objects.filter(
            deviceId=deviceId, createTime__range=(startTime, endTime))
    else:
        result = Logger.objects.filter(
            deviceId=deviceId, createTime__range=(endTime, startTime))

    resultData = []
    for item in result:
        resultData.append(item.content)

    return JsonResponse(resultData)


# 定时清理日志数据任务
try:
    scheduler = BackgroundScheduler()
    # 每天清除1天前的日志数据

    @register_job(scheduler, "interval", days=1, id='clear_logger_job')
    def clear_logger():
        # 筛选数据1天前
        filter_time = datetime.datetime.now()-datetime.timedelta(days=1)
        Logger.objects.filter(createTime__lt=(filter_time)).delete

    register_events(scheduler)
    scheduler.start()
except Exception as e:
    scheduler.shutdown()
